<template>
    <div>
        <div class="chatbox">
            <div class="chat-name">
                {{toName}}
            </div>
            <div class="chat-content" id="dialogue_box">
                <div class="clearfix" v-for="(item,index) in chatList" :key="index" :class="[item.wz ? 'chat-left' : 'chat-right']">
                    <img :src="$imgPath(item.sendUser.headImg)" alt="">
                    <div class="pointer-left" :class="[item.wz ? 'pointer-left' : 'pointer-right']"  v-html="handleMsg(item.descript)">
                    </div>
                </div>
            </div>
            <div class="chat-fasong clearfix">
                <ul class="faces-ul" v-if="showEmoji">
                    <li v-for="(value,key) in emojiMap" :key="key" @click="clickFace(key)" class="webim-emoji-item">
                        <img :src="value" alt="emoj"/>
                    </li>
                </ul>
                <div class="chat-tt">
                    <img class="bq" src="../../assets/img/bq.png" alt="" @click="showEmoji = !showEmoji">
                    <img class="pic" src="../../assets/img/pic.png" alt="">
                    <input type="file" ref="avatarInput2" id="file-Input" @change="clickImg()">
                </div>
                <div class="chat-text">
                    <textarea v-model="chat_message" name="" id="" cols="30" rows="10"></textarea>
                </div>
                <div class="chat-button">
                    <span @click="sendTextMsg()">
                        发送
                    </span>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import apiHttp from '../../api/index'
import ee_1 from '../../assets/faces/ee_1.png'
import ee_2 from '../../assets/faces/ee_2.png'
import ee_3 from '../../assets/faces/ee_3.png'
import ee_4 from '../../assets/faces/ee_4.png'
import ee_5 from '../../assets/faces/ee_5.png'
import ee_6 from '../../assets/faces/ee_6.png'
import ee_7 from '../../assets/faces/ee_7.png'
import ee_8 from '../../assets/faces/ee_8.png'
import ee_9 from '../../assets/faces/ee_9.png'
import ee_10 from '../../assets/faces/ee_10.png'
import ee_11 from '../../assets/faces/ee_11.png'
import ee_12 from '../../assets/faces/ee_12.png'
import ee_13 from '../../assets/faces/ee_13.png'
import ee_14 from '../../assets/faces/ee_14.png'
import ee_15 from '../../assets/faces/ee_15.png'
import ee_16 from '../../assets/faces/ee_16.png'
import ee_17 from '../../assets/faces/ee_17.png'
import ee_18 from '../../assets/faces/ee_18.png'
import ee_19 from '../../assets/faces/ee_19.png'
import ee_20 from '../../assets/faces/ee_20.png'
import ee_21 from '../../assets/faces/ee_21.png'
import ee_22 from '../../assets/faces/ee_22.png'
import ee_23 from '../../assets/faces/ee_23.png'
import ee_24 from '../../assets/faces/ee_24.png'
import ee_25 from '../../assets/faces/ee_25.png'
import ee_26 from '../../assets/faces/ee_26.png'
import ee_27 from '../../assets/faces/ee_27.png'
import ee_28 from '../../assets/faces/ee_28.png'
import ee_29 from '../../assets/faces/ee_29.png'
import ee_30 from '../../assets/faces/ee_30.png'
import ee_31 from '../../assets/faces/ee_31.png'
import ee_32 from '../../assets/faces/ee_32.png'
import ee_33 from '../../assets/faces/ee_33.png'
import ee_34 from '../../assets/faces/ee_34.png'
import ee_35 from '../../assets/faces/ee_35.png'
export default {
    props:["detailObj","toCode","toName","toUserImg","toUserId"],
    data(){
        return{
            chatList:[],        // 聊天记录
            chat_message:'',    // 聊天内容
            showEmoji:false,     // 表情
            emojiMap: {
                '[):]': ee_1,
                '[:D]': ee_2,
                '[;)]': ee_3,
                '[:-o]': ee_4,
                '[:p]': ee_5,
                '[(H)]': ee_6,
                '[:@]': ee_7,
                '[:s]': ee_8,
                '[:$]': ee_9,
                '[:(]': ee_10,
                '[:\'(]': ee_11,        
                '[:|]': ee_12,
                '[(a)]': ee_13,
                '[8o|]': ee_14,
                '[8-|]': ee_15,
                '[+o(]': ee_16,
                '[<o)]': ee_17,
                '[|-)]': ee_18,
                '[*-)]': ee_19,
                '[:-#]': ee_20,
                '[:-*]': ee_21,
                '[^o)]': ee_22,
                '[8-)]': ee_23,
                '[(|)]': ee_24,
                '[(u)]': ee_25,
                '[(S)]': ee_26,
                '[(*)]': ee_27,
                '[(#)]': ee_28,
                '[(R)]': ee_29,
                '[({)]': ee_30,
                '[(})]': ee_31,
                '[(k)]': ee_32,
                '[(F)]': ee_33,
                '[(W)]': ee_34,
                '[(D)]': ee_35,
            },
        }
    },
    watch:{
        toCode(newVal,oldVal){
            
        }
    },
    mounted(){
        let self = this
        setTimeout(()=>{
            self.$imoption.user = this.detailObj.code
            self.openHx()
        },2000)
    },
    methods:{
        // 获取聊天的历史记录
        listByChat(){
            let parmes = {
                toUserId:this.toUserId
            }
            apiHttp.apiCenter.listByChat(parmes,resp=>{
                if(resp.code == 200){
                    for(let i in resp.data.content){
                        if(this.toUserId == resp.data.content[i].sendUser.id){
                            resp.data.content[i].wz = true
                        }else{
                            resp.data.content[i].wz = false
                        }
                        this.chatList.unshift(resp.data.content[i])
                    }
                    this.scrollTopDiv()
                }
            })
        },
        // 开启环信
        openHx(){
            var self = this
            self.$imconn.open(this.$imoption)
            self.$imconn.listen({
                onOpened(message){          //连接成功回调
                    console.log('用户已上线')
                },
                onTextMessage(message){    //收到文本消息
                    console.log(message)
                    let msg = {
                        descript:message.data,
                        wz:true,
                        createTime:'',
                        sendUser:{
                            headImg:self.toUserImg
                        }
                    }
                    if(message.from == self.toCode){
                        self.chatList.push(msg)
                    }
                },
                onPictureMessage(message) {     // 接收图片消息
                    let msg = {
                        descript:`<img src="${self.$imgPath(message.url)}">`,
                        wz:true,
                        createTime:'',
                        sendUser:{
                            headImg:self.toUserImg
                        }
                    }
                    if(message.from == self.toCode){
                        self.chatList.push(msg)
                    }
                    console.log(message)
                }
            })
        },
        // 发送消息
        sendTextMsg(){
            let self = this
            if(self.chat_message == ""){
                return
            }
            let id = this.$imconn.getUniqueId() 
            let msg = new WebIM.message('txt', id)
            msg.set({
                msg: self.chat_message,                  // 消息内容
                to: self.toCode,                          // 接收消息对象（用户id）
                roomType: false,
                success: function (id, serverMsgId) {
                    self.messageSend(self.toCode,"",self.chat_message,"",200)
                    let msg = {
                        descript:self.chat_message,
                        wz:false,
                        createTime:'',
                        type:200,
                        sendUser:{
                            headImg:self.detailObj.headImg
                        }
                    }
                    self.chatList.push(msg)
                    self.chat_message = ''
                    self.scrollTopDiv()
                },
                fail: function(e){
                    console.log("Send private text error");
                }
            })
            msg.body.chatType = 'singleChat'
            this.$imconn.send(msg.body)
        },
        // 表情直接发送
        clickFace(key){
            let self = this
            let id = this.$imconn.getUniqueId() 
            let msg = new WebIM.message('txt', id)
            msg.set({
                msg: key,                  // 消息内容
                to: self.toCode,                          // 接收消息对象（用户id）
                roomType: false,
                success: function (id, serverMsgId) {
                    self.messageSend(self.toCode,"",key,"",202)
                    let msg = {
                        descript:key,
                        wz:false,
                        createTime:'',
                        type:202,
                        sendUser:{
                            headImg:self.detailObj.headImg
                        }
                    }
                    self.showEmoji = !self.showEmoji
                    self.chatList.push(msg)
                    self.scrollTopDiv()
                },
                fail: function(e){
                    console.log("Send private text error");
                }
            })
            msg.body.chatType = 'singleChat'
            this.$imconn.send(msg.body)
        },
        // 发送图片
        clickImg(){
            let self = this
            let id = self.$imconn.getUniqueId() 
            let msg = new WebIM.message('img', id)
            let input = document.getElementById('file-Input')
            let allowType = {
                'jpg': true,
                'gif': true,
                'png': true,
                'bmp': true
            }
            let file = WebIM.utils.getFileUrl(input)
            if(file.filetype.toLowerCase() in allowType){
                msg.set({
                    ext:{},
                    to: self.toCode,                          // 接收消息对象（用户id）
                    roomType: false,
                    apiUrl: self.$imoption.apiUrl,
                    file: file,
                    chatType:'singleChat',
                    roomType: false,
                    onFileUploadError: function (e) {      // 消息上传失败
                        console.log('失败');
                    },
                    onFileUploadComplete: function (e) {   // 消息上传成功
                        console.log('上传成功');
                    },
                    success: function (data) {       
                        let fd = new FormData()
                        fd.append('model','user/chat')
                        if (self.$refs.avatarInput2.files.length !== 0) {
                            fd.append('file', self.$refs.avatarInput2.files[0])
                        }
                        apiHttp.apiCenter.uploadImg(fd,resp=>{
                            if(resp.code = 200){
                                let msg = {
                                    descript:`<img src="${self.$imgPath(resp.data.url)}">`,
                                    wz:false,
                                    createTime:'',
                                    type:202,
                                    sendUser:{
                                        headImg:self.detailObj.headImg
                                    }
                                }
                                self.chatList.push(msg)
                                self.messageSend(self.toCode,"",`<img src="${self.$imgPath(resp.data.url)}">`,"",202)
                                self.scrollTopDiv()
                            }
                        })
                        console.log('发送成功')
                    },
                    flashUpload: WebIM.flashUpload
                })
                self.$imconn.send(msg.body)
            }
        },
        //存储消息再本地服务器
        messageSend(userCode,title,descript,path,type){
            let params = {
                descript:descript,
				title:title,
				url:path,
				userCode:userCode,
				type:type
            }
            apiHttp.apiCenter.messageSend(params,resp=>{
                if(resp.code == 200){
                
                }
            })
        },
        // 滚动条到达底部
        scrollTopDiv(){
            this.$nextTick(function(){
                var div = document.getElementById('dialogue_box')
                div.scrollTop = div.scrollHeight
            })
        },
        // 表情过滤
        handleMsg (msg) {
            if (this.emojiMap[msg]) {
                return `<img src="${this.emojiMap[msg]}"/>`
            } else {
                return msg
            }
        },
        // 清空数组
        clearChatList(){
            this.chatList = []
        }
    }
}
</script>

<style scoped>
.chatbox{
    position: relative;
}
.chat-name{
    height: 60px;
    font-size: 18px;
    color: #333;
    text-align: left;
    line-height: 60px;
    background-color: #fff;
    padding-left: 40px;
    border-radius: 10px 10px 0 0;
    box-shadow:0px 15px 10px -15px #000;
}
.chat-content{
    padding: 0 20px;
    background-color: #f8f8f8;
    min-height: 430px;
    max-height: 430px;
    overflow-y: auto;
}
.chat-left,.chat-right{
    padding: 20px 0 0 0;
}
.chat-left img{
    width: 48px;
    height: 48px;
    border-radius: 50%;
    float: left;
}
.pointer-left{
    float: left;
    font-size: 14px;
    background-color: #fff;
    margin-left: 15px;
    padding: 5px 10px;
    border-radius: 10px;
    margin-top: 7px;
    max-width: 497px;
}
.chat-right img{
    width: 48px;
    height: 48px;
    border-radius: 50%;
    float: right;
}
.pointer-right{
    float: right;
    font-size: 14px;
    background-color: #D84E4D;
    margin-right: 15px;
    padding: 5px 10px;
    border-radius: 10px;
    margin-top: 7px;
    max-width: 497px;
    color: #fff;
}
.chat-fasong{
    height: 170px;
    background-color: #f8f8f8;
    border-radius: 0 0 10px 10px;
    padding-bottom: 10px;
    position: relative;
}
.faces-ul{
    position: absolute;
    left: 0;
    top: -80px;
    height: 80px;
    width: 100%;
    padding: 2%;
    z-index: 999;
    background-color: #fff;
}
.webim-emoji-item{
    display: inline-block;
}
.chat-tt{
    position: relative;
    height: 39px;
    border-top: rgba(238,238,238,1) solid 1px;
}
.chat-tt .bq{
    width: 25px;
    margin-left: 20px;
    margin-top: 8px;
    float: left;
}
.chat-tt .pic{
    width: 30px;
    margin-left: 20px;
    margin-top: 5px;
    float: left;
}
.chat-text{
    height: 80px;
    width: 100%;
}
.chat-text textarea{
    height: 60px;
    border: none;
    padding: 10px;
    width: 100%;
    background-color: #f8f8f8;
    font-size: 14px;
    color: #333;
}
.chat-button{
    height: 30px;
    width: 100%;
}
.chat-button span{
    height: 30px;
    display: inline-block;
    width: 80px;
    line-height: 30px;
    background-color: #D84E4D;
    text-align: center;
    font-size: 14px;
    color: #fff;
    border-radius: 5px;
    float: right;
    margin-right: 20px;
}
#file-Input{
    position: absolute;
    left: 65px;
    top: 8px;
    width: 30px;
    opacity: 0;
    z-index: 99;
}
</style>
